/*
 * Middleware
 * Copyright (C) 2010/11
 * Riccardo Pulvirenti, Giuseppe Ravidà, Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: worker_discovery.hpp
 */

#ifndef _WORKER_DISCOVERY_HPP_
#define _WORKER_DISCOVERY_HPP_

#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <vector>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <exception>
#include <boost/lexical_cast.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <cstdlib>

#include "runner.hpp"
#include "worker_descriptor.hpp"
#include "task_descriptor.hpp"
#include "common_types.hpp"
#include "xml_syn_logging.hpp"

//-----------------------------------------------------------------------------
// Enum, struct, aliases
namespace middleware {
/*! \struct DiscoveryConfig
 * \brief Configuration for WorkerDiscovery.
 *
 * Configuration structure for WorkerDiscovery.
 */
typedef struct {
	/*!
	 * Represents the Ip v4 address the WorkerDiscovery will bind to in order
	 * to listen for incoming WorkerDescriptor from Worker of other peers.
	 */
	std::string disc_ip_tow_bind; /* IP to workers (not used to bind) */
	/*!
	 * Represents the TCP Port the WorkerDiscovery will bind to in order
	 * to listen for incoming WorkerDescriptor from Worker of other peers.
	 */
	std::string disc_port_tow_bind; /* Port to workers (bind) */
	/*!
	 * Logger
	 */
	logging::XmlSynLogger* _xml_logger;
} DiscoveryConfig;
}
//-----------------------------------------------------------------------------
// Constants
namespace middleware {
/*!
 * Lowest port used to bind for listening for incoming data.
 */
const unsigned int kWorkerDiscoveryMinManPort = 1051;
/*!
 * Highest port used to bind for listening for incoming data.
 */
const unsigned int kWorkerDiscoveryMaxManPort = 65536 - 1;
/*!
 * Etiquette for output.
 */
const std::string kWorkerDiscoveryEtq = "DISC:      ";
}
//-----------------------------------------------------------------------------
// Class definitions
namespace middleware {
/*! \class WorkerDiscovery
 * \brief Class representing the WorkerDiscovery of a peer.
 *
 * This class implements the functionalities exposed by the WorkerDiscovery.
 */
class WorkerDiscovery : public Runner {
	/*!
	 * To let the proxy operate correctly.
	 */
	friend class WorkerDiscoveryProxy;
public:
	/*!
	 * Constructs a well configured WorkerDescriptor specifying the known
	 * peers and the desired configuration.
	 * \param PK PeersKnowledge representing the set of known peers, that are
	 * the neighbours of this peer.
	 * \param conf DiscoveryConfig configuration for WorkerDiscovery.
	 */
	WorkerDiscovery(PeersKnowledge PK, DiscoveryConfig conf);
	/*!
	 * Destructor.
	 */
	~WorkerDiscovery();
	/*!
	 * Runs WorkerDiscovery. If another thread was running, it will be destoyed.
	 */
	void run() {
		this->_disc_thread.reset();
		this->_disc_thread = boost::shared_ptr<boost::thread>(
				new boost::thread(
						boost::bind(&WorkerDiscovery::exec, this)));
	}
	/*!
	 * Joins caller thread to WorkerDiscovery execution thread and wait for
	 * it to finish.
	 */
	void join() {
		(this->_disc_thread)->join();
	}
private:
	/*!
	 * Creates a casual port number > 1050 and gets it. Orphan
	 */
	std::string createPort();
	/*!
	 * Execution function.
	 */
	void exec();
	/*!
	 * Called everytime that a worker descriptor arrives.
	 */
	void ManageWorkerDescriptor(WorkerDescriptor wd);
	/*!
	 * Called by manager (proxied), the function returns the best fit worker
	 * for a particular task to be executed.
	 */
	WorkerDescriptor worker_getter(const TaskDescriptor& td);
	/*!
	 * When looking for the current best worker, this procedure returns it by
	 * querying the Peers knowledge.
	 */
	WorkerDescriptor GetCurrentBestWorkerDesc();
	/*!
	 * Initialization routine with user.
	 */
	void bonjour();
	/*!
	 * Configuration for Discovery.
	 */
	DiscoveryConfig _config;
	/*!
	 * Underlaying thread.
	 */
	boost::shared_ptr<boost::thread> _disc_thread;
	/*!
	 * Knowledge of neighboorhood.
	 */
	PeersKnowledge _pk;
};
}

#endif
